package com.uy.cuantoconocesdeuruguay.utiles;

import java.util.HashMap;
import java.util.Iterator;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.uy.cuantoconocesdeuruguay.controllers.GoogleAnalyticsTracker;
import com.uy.cuantoconocesdeuruguay.server.ImagesFetcher;

@SuppressLint("NewApi")
public class ImageLoader {
	private static final HashMap<String, Drawable> cache = new HashMap<String, Drawable>();
	private static final HashMap<ImageView, AsyncTask<ImageView, Void, Drawable>> loaderFor = new HashMap<ImageView, AsyncTask<ImageView, Void, Drawable>>();
	private static final Object mutex = new Object();
	
	//CACHE CLEANER FOR MEMORY MAINTENANCE
	static{
		AsyncTask<Void, Void, Void> cacheCleaner = new AsyncTask<Void, Void, Void>(){
			@Override
			protected Void doInBackground(Void... params) {
				while (true){
					synchronized (mutex) {
						if (cache != null && !cache.isEmpty()){
							Iterator<String> iterator = cache.keySet().iterator();
							String key = iterator.next();
							cache.remove(key);
						}
					}
					try {
						Thread.sleep(10000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		};
		if (android.os.Build.VERSION.SDK_INT > 10) {
			cacheCleaner.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
		}else{
			cacheCleaner.execute();
		}
	}
	
	public static void loadImageOn(final Activity activity, final ImageView view, final String imageURL){
		Drawable cachedDrawable;
		synchronized (mutex) {
			cachedDrawable = cache.get(imageURL);
		}
		if (cachedDrawable != null){
			view.setImageDrawable(cachedDrawable);
		}
		AsyncTask<ImageView, Void, Drawable> asyncTask = new AsyncTask<ImageView, Void, Drawable>() {
    		private ImageView holderView;
    		@Override
    		protected Drawable doInBackground(ImageView... params) {
    			holderView = params[0];
    	        return new ImagesFetcher().fetchImage(activity, imageURL, false);
    		}
    		@Override
    		protected void onPostExecute(Drawable result) {
    			synchronized (mutex) {
        			cache.put(imageURL, result);					
				}
    			holderView.setImageDrawable(result);
    		}
		};
		if (android.os.Build.VERSION.SDK_INT > 10) {
			try{
				asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, view);
			}catch (Exception e){
				GoogleAnalyticsTracker.trackException(activity, e);
				asyncTask.execute(view);
			}
		}else{
			asyncTask.execute(view);
		}
	}
	
	public static void loadImageOn(final Activity activity, final ImageView view, final String imageURL,final ProgressBar loader){
		Drawable cachedDrawable;
		synchronized (mutex) {
			cachedDrawable = cache.get(imageURL);
		}
		if (cachedDrawable != null){
			view.setImageDrawable(cachedDrawable);
			loader.setVisibility(View.GONE);
		}
		AsyncTask<ImageView, Void, Drawable> cachedLoader;
		synchronized (mutex) {
			cachedLoader = loaderFor.get(view);
		}
		if (cachedLoader != null){ 
			cachedLoader.cancel(true);
		}
		AsyncTask<ImageView, Void, Drawable> asyncTask = new AsyncTask<ImageView, Void, Drawable>() {
    		private ImageView holderView;
    		@Override
    		protected Drawable doInBackground(ImageView... params) {
    			holderView = params[0];
    	        return new ImagesFetcher().fetchImage(activity, imageURL, false);
    		}
    		@Override
    		protected void onPostExecute(Drawable result) {
    			synchronized (mutex) {
        			cache.put(imageURL, result);	
        			loaderFor.remove(view);				
				}
    			if (loader.getVisibility() == View.VISIBLE){
	    			holderView.setImageDrawable(result);
	    			loader.setVisibility(View.GONE);
    			}
    		} 
		};
		synchronized (mutex) {
			loaderFor.put(view, asyncTask);
		}
		if (android.os.Build.VERSION.SDK_INT > 10) {
			try{
				asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, view);
			}catch (Exception e){
				GoogleAnalyticsTracker.trackException(activity, e);
				try{
					asyncTask.execute(view);
				}catch (Exception x){
					GoogleAnalyticsTracker.trackException(activity, x);
				}
			}
		}else{
			asyncTask.execute(view);
		}
	}

	public static void loadImageOn(final Activity activity, final ImageView view, final int resImage,final ProgressBar loader){
		AsyncTask<ImageView, Void, Drawable> cachedLoader;
		synchronized (mutex) {
			cachedLoader = loaderFor.get(view);
		}
		if (cachedLoader != null){ 
			cachedLoader.cancel(true);
		}
		AsyncTask<ImageView, Void, Drawable> asyncTask = new AsyncTask<ImageView, Void, Drawable>() {
    		private ImageView holderView;
    		@Override
    		protected Drawable doInBackground(ImageView... params) {
    			holderView = params[0];
    			return null;
    		}
    		@Override
    		protected void onPostExecute(Drawable result) {
    			synchronized (mutex) {
        			loaderFor.remove(view);				
				}
    			holderView.setImageResource(resImage);
    			loader.setVisibility(View.GONE);
    		} 
		};
		synchronized (mutex) {
			loaderFor.put(view, asyncTask);
		}
		if (android.os.Build.VERSION.SDK_INT > 10) {
			try{
				asyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, view);
			}catch (Exception e){
				GoogleAnalyticsTracker.trackException(activity, e);
				try{
					asyncTask.execute(view);
				}catch (Exception x){
					GoogleAnalyticsTracker.trackException(activity, x);
				}
			}
		}else{
			asyncTask.execute(view);
		}
	}
}
